<template>
  <div id="app">
    <input v-model="message" placeholder="Type your message" />
    <button @click="sendMessage">Send</button>
    <br/>
    <el-input
      v-model="outputRef"
      style="width: 100%"
      autosize
      type="textarea"
    />
    <br/>
    <!-- <div v-for="(item, index) in useRdat.topicRecordList" :key="index">
      <span>{{item.conver_id}}</span>
    </div> -->
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import axios from "axios";
import useRdatStore from '/src/stores/index.js'
const useRdat = useRdatStore()

const message = ref("");
const response = ref("");

let eventSource = null;

const outputRef = ref("");
const currentText = ref("");
const topicRecordList = ref([])

onMounted(() => {
  eventSource = new EventSource("/api/stream");
  eventSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    updateResponse(data);
  };
  eventSource.onerror = (event) => {
    eventSource.close();
  }
});

onBeforeUnmount(() => {
  if (eventSource) {
    eventSource.close();
  }
});

const sendMessage = () => {
  console.log(message.value);
  message.value = "";
};

const updateResponse = (data) => {
  const newTextChunk = data.conver_id;
  currentText.value += newTextChunk;
  if(currentText.value.length > 100) {
    eventSource.close();
  }
  useRdat.topicRecordList.pop()
  useRdat.topicRecordList.push(data)
};

// 监听整个文本的变化，然后改变当前显示的值
watch(currentText, (newValue, oldValue) => {
  if (outputRef.value.length < currentText.value.length) {
    // 截取剩下的部分的字符串
    let subStr = currentText.value.substring(
      outputRef.value.length,
      currentText.value.length
    );
    subStr.split("").forEach((char, index) => {
      setTimeout(() => {
        outputRef.value += char;
      }, 100 * index); // 每个字符延迟100毫秒显示
    });
  }
});
</script>